package com.lkd.handler;

/**
 * @author zystart
 * @create 2022-09-19 19:13
 */

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 补货工单完成处理
 */
@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class TaskSupplyMsgHandler implements MsgHandler {
    @Autowired
    private VendingMachineService vendingMachineService;

    @Autowired
    private ChannelService channelService;

    /**
     * 更新货道数据修改状态
     *
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        //解析信息
        SupplyContract contract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //更新货道数据
        updateChannels(contract);
        //修改状态
        vendingMachineService.updateStatus(contract.getInnerCode(), VMSystem.VM_STATUS_RUNNING);
    }

    /**
     * 更新货道数据
     *
     * @param contract
     */
    private void updateChannels(SupplyContract contract) {
        //补货货道数据
        List<SupplyChannel> supplyData = contract.getSupplyData();
        //售货机编号
        String innerCode = contract.getInnerCode();
        //保存数据库
        List<ChannelEntity> entityList = channelService.getChannelesByInnerCode(innerCode);
        for (ChannelEntity channel : entityList) {
            List<ChannelEntity> list = supplyData.stream().map(new Function<SupplyChannel, ChannelEntity>() {
                @Override
                public ChannelEntity apply(SupplyChannel supplyChannel) {
                    if (channel.getChannelCode().equals(supplyChannel.getChannelId())) {
                        int nowNumber = supplyChannel.getCapacity() + channel.getCurrentCapacity();
                        if (channel.getMaxCapacity() >= nowNumber)
                            channel.setCurrentCapacity(nowNumber);
                        channel.setLastSupplyTime(LocalDateTime.now());
                        channelService.updateById(channel);
                    }
                    return channel;
                }
            }).collect(Collectors.toList());
        }
    }
}
